package com.event.controller;

import com.event.pojo.dto.UserDTO;
import com.event.pojo.entity.User;
import com.event.result.Result;
import com.event.service.UserService;
import com.event.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/user")
@Validated
@Slf4j
public class UserController {
	
	@Resource
	private UserService userService;
	
	/**
	 * 获取用户信息
	 */
	@GetMapping("/userinfo")
	public Result<User> getUser() {
		log.info("获取当前登录用户id：{}", Optional.ofNullable(ThreadLocalUtil.get()));
		return Result.success(userService.getById(ThreadLocalUtil.get()));
	}
	
	/**
	 * 用户注册
	 */
	@PostMapping("/register")
	public Result<?> register(@Pattern(regexp = "^\\S{5,16}$") String username,
	                          @Pattern(regexp = "^\\S{5,16}$") String password) {
		log.info("用户注册：{},{}", username, password);
		userService.register(username, password);
		return Result.success();
	}
	
	/**
	 * 登录
	 */
	@PostMapping("/login")
	public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username,
	                            @Pattern(regexp = "^\\S{5,16}$") String password) {
		log.info("用户登录：{},{}", username, password);
		return Result.success(userService.login(username, password));
	}
	
	/**
	 * 修改用户信息
	 */
	@PutMapping("/update")
	public Result<?> update(@RequestBody @Validated User user) {
		log.info("修改用户信息：{}", user);
		userService.update(user);
		return Result.success();
	}
	
	/**
	 * 修改图像
	 */
	@PutMapping("/updateAvatar")
	public Result<?> updateAvatar(@RequestBody @URL String url) {
		log.info("修改图像：{}", url);
		userService.updateAvatarAvatar(url);
		return Result.success();
	}
	
	
	/**
	 * 修改密码
	 */
	@PutMapping("/updatePwd")
	public Result<?> updatePwd(@RequestBody UserDTO userDTO) {
		log.info("修改密码：{}", userDTO);
		userService.updatePwd(userDTO);
		return Result.success();
	}
}
